package com.lzw.security.config;

import com.lzw.security.mapper.UserMapper;

import com.lzw.security.util.JwtTokenUtil;
import com.lzw.security.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

/**
 * @ClassNmae MyUserDeatisService
 * @Description TODO
 * @Author 14631
 **/
@Component
public class MyUserDeatisService implements UserDetailsService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Override
	public UserDetails loadUserByUsername(String username) {
		com.lzw.security.entity.User  user =  userMapper.checkUser(username);
		if(user==null){
			register(username,user);
		}
		user = userMapper.checkUser(username);
		System.out.println("user:"+user.getOpenId());
//		String token = JwtTokenUtil.generateToken(user); 登录成功处理器做
//		redisUtil.set(token,user.getOpenId());
		return returnUser(user.getOpenId(),user.getPassword(),"ROLE_User,ROLE_Admin");
	}

	public void register(String openId, com.lzw.security.entity.User user){
		user = new com.lzw.security.entity.User();
		user.setOpenId(openId);
		user.setPassword(passwordEncoder.encode("546100"));
		int register = userMapper.register(user);
	}
	public User returnUser(String openId, String password, String power){
		return new User(openId,password,
				true,true,true,true,
				AuthorityUtils.commaSeparatedStringToAuthorityList(power));
	}
}
